package com.jinhao.crowd.mvc.handler;

import com.jinhao.crowd.entity.Menu;
import com.jinhao.crowd.service.api.MenuService;
import com.jinhao.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2021/10/1.
 *
 * @author Valar Morghulis
 */

@RestController
public class MenuHandler {

    @Autowired
    private MenuService menuService;

    /**
     * 删除menu
     *
     * @param id
     * @return
     */
    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id) {

        menuService.removeMenu(id);

        return ResultEntity.successWithoutData();
    }


    /**
     * 更新menu
     *
     * @param menu
     * @return
     */
    @RequestMapping("/menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu) {

        menuService.updateMenu(menu);

        return ResultEntity.successWithoutData();
    }

    /**
     * 添加一个menu
     *
     * @param menu
     * @return
     */
    //@ResponseBody
    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu) {
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    //@ResponseBody
    @RequestMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getAll() {

        // 获取到全部menu对象
        List<Menu> menuList = menuService.getAll();

        // 声明一个根节点
        Menu root = null;

        // 创建 Map 对象用来存储 id 和 Menu 对象的对应关系便于查找父节点
        Map<Integer, Menu> menuMap = new HashMap<>();

        //遍历menuList，填充menuMap
        for (Menu menu : menuList) {

            Integer id = menu.getId();

            menuMap.put(id, menu);
        }

        // 再次遍历，查找根节点，组装父子节点
        for (Menu menu : menuList) {

            // 获取到当前menu对象的pid
            Integer pid = menu.getPid();

            if (pid == null) {
                // 如果当前menu对象的pid==null,则为根节点
                root = menu;

                // 根节点没有父节点，跳出此循环
                continue;
            }

            // 其余对象都拥有父节点，根据pid找到父节点并将对象添加到父节点的children属性中
            Menu father = menuMap.get(pid);
            father.getChildren().add(menu);
        }

        return ResultEntity.successWithData(root);
    }
}
